<template>
	<div id="assign">
		<!-- 遮罩层 -->
		<div class="cover"></div>
		<div class="assign-wrap">
			<!-- 选择主题区域 Start-->
			<div class="assign-title">
				<span class="assign-span">{{assignTitle}}</span>
				<i class="el-icon-error" @click="cancel"></i>
			</div>
			<div id="choice">
				<div class="leftshow">
					<!-- 搜索框 -->
					<i class="el-icon-search left-search"></i>
					
					<span class="place-text">{{searchTipText}}</span>
					
					<!-- <input id="search-user" v-model="searchwords" :placeholder="searchTipText"> -->
					<input id="search-user" v-model="searchwords" @focus="placeMove('focus')" @blur="placeMove('blur')">
					<!-- 搜索结果展示组件 -->
					<transition name="slide">
						<assign-search v-show="searchwords!=''" :type="type" :searchword="searchwords" @triggerSelect="selectSearchChild"></assign-search>
					</transition>

					<!-- tab切换 -->
					<div class="right-tab" @click="changeTab($event)" v-if="type!='lesson'">
						<span class="by-people by-sec" data-type="user" v-if="userShowTab.user">按部门和学员</span>
						<span class="by-group" data-type="group" v-if="userShowTab.group">按用户组</span>
						<span class="by-position" data-type="position" v-if="userShowTab.position">按职位</span>
					</div>

					<div class="left-main">
						<div class="left-nav">
							<span class="nav-root nav-com" v-if="type=='lesson'">全部课程</span>
							<span class="nav-root nav-com" v-else>公司名称</span>

							<template v-for="navItem in navInfo">
								<i class="el-icon-arrow-right"></i>
								<span class="nav-com" :data-iden="navItem.uuid">{{navItem.name}}</span>
							</template>
						</div>
						<div class="left-all" v-loading="loading">
							<ul class="left-ul left-ul-com" :class="{'user-height':type!='lesson'}" id="left-lesson">
								<li @click.prevent="selectAll">
									<el-checkbox  class="checkall" v-model="checkall[type]">全选</el-checkbox>
									<!-- <input type="checkbox" class="checkall" v-model="checkall[type]"> -->
									<!-- <span class="checkspan">全选</span> -->
								</li>

								<!-- 按课程指派列表 -->
								<template v-if="type=='lesson'">
									<!-- 遍历课程分类 -->
									<li class="lesson-type" v-for="item in assignShowData.lessonType" :key="item.uuid">
										<span class="left-name left-type">
			                    			<i class="icon iconfont icon-wenjian fa-folder"></i>
			                    			<strong>{{item.name}}</strong>
			                    		</span>
										<span class="left-down" @click="next(item.uuid,item.name,$event)">
			                    			<i class="icon iconfont icon-bumen"></i>
			                    			下级
			                    		</span>
									</li>
									<!-- 遍历课程名 -->
									<li class="lesson-name" v-for="item in assignShowData.lessonName" :key="item.uuid" @click.prevent="selectLesson(item.uuid,item.title,item)">
										<el-checkbox  class="xcheck" v-model="checkStatus[item.uuid]">{{item.title}}</el-checkbox>
										<!-- <input type="checkbox" class="xcheck" v-model="checkStatus[item.uuid]">
										<span class="left-name"><strong>{{item.title}}</strong></span> -->
									</li>
								</template>

								<!-- 按用户、部门指派列表 -->
								<template v-else-if="type=='user'">
									<!-- 遍历部门 -->
									<li class="lesson-name" v-for="(item,index) in assignShowData.deptList" :key="index">
										<el-checkbox v-if="deptCheckbox" :disabled=item.disable class="deptCheck" v-model="checkStatus[item.uuid]" @click.native.prevent="selectLesson(item.uuid,item.dept_name,item,$event)">{{item.dept_name}}</el-checkbox>

										<el-checkbox v-else  class="deptCheck" v-model="checkStatus[item.uuid]" disabled>{{item.dept_name}}</el-checkbox>
								
										<span class="left-down" :class="{'disable-click':checkStatus[item.uuid] || item.has_children<=0}" @click="next(item.uuid,item.dept_name,$event)">
			                    			<i class="icon iconfont icon-bumen"></i>
			                    			下级
			                    		</span>
									</li>
									<!-- 遍历用户名 -->
									<li class="lesson-name" v-for="item in assignShowData.userList" :key="item.uuid" @click.prevent="selectLesson(item.uuid,item.user_name,item)">
										<el-checkbox  class="xcheck" v-model="checkStatus[item.uuid]">{{item.user_name}}</el-checkbox>
									</li>
								</template>

								<!-- 按用户组、职位指派列表 -->
								<template v-else-if="type=='group' || type=='position'">
									<!-- 遍历用户组 -->
									<li class="group" v-for="item in assignShowData.showList" @click.prevent="selectLesson(item.uuid,item.name,item)">
										<el-checkbox  class="xcheck" v-model="checkStatus[item.uuid]">{{item.name}}</el-checkbox>
										<!-- <input type="checkbox" class="xcheck" v-model="checkStatus[item.uuid]">
										<span class="right-name">{{item.name}}</span> -->
										<div class="group-desc">{{item.nameList}}</div>
									</li>
									
								</template>

							</ul>
						</div>
					</div>
					<!-- <div class="left-btm">
		                <span class="left-sec">0</span>/<span class="left-all">60</span>
		            </div> -->
				</div>
				<!-- 右侧数据展示区域 -->
				<div class="rightshow">
					<div class="right-wrap">
						<div class="right-all">
							<!-- <ul class="right-ul right-ul-com"> -->
							<transition-group name="right-list" tag="ul" class="right-ul right-ul-com">
								<li class="lesson-name right-list-item" v-for="rightItem in rightShowInfo" :key="rightItem.uuid">
									<span class="right-name">{{rightItem.title}}</span>
									<i class="el-icon-circle-close-outline lesson-del" @click="deleteLesson(rightItem.uuid)"></i>
								</li>
							</transition-group>
							<!-- </ul> -->
						</div>
					</div>
				</div>
			</div>
			<!-- 选择主题区域 End-->
			<div class="assign-button">
				<button type="button" class="el-button el-button--default" @click="cancel"><span>取消</span></button>
				<button type="button" class="el-button el-button--primary" @click="ok"><span>确定</span></button>
			</div>
		</div>
	</div>
</template>
<script>

import assignSearch from "./AssignSearch.vue" //搜索结果展示组件
export default {
	data () {
		return {
			/*user: mockUser,
			lesson: mockLesson,*/
			assignShowData: '',
			type          : this.assignType, //指派类型
			record        : [], //记录选中条目的uuid
			recordAll     : [], //记录选中条目全部数据
			checkStatus   : {}, //记录每条数据的复选框选中状态
			rightShowInfo : [], //右侧显示选中的信息
			navInfo       : [], //面包屑导航
			// checkall      : false, //是否全选
			checkall : {  //课程全选状态
				'lesson'  : false,
				'user'    : false,
				'group'   : false,
				'position': false
			},
			searchwords   : '', //搜索的文字
			requestStatus : {	//判断切换tab时，是否需要请求默认数据
				'user'     :true,	//部门和学员
				'group'    :true,	//用户组
				'position' :true	//职位
			},
			loading:false,
			// =========测试数据
			/*lessonExam: mockLesson,
			test: {
				"lessonType": [{
					"uuid": "3B67C987-5863-4049-BB87-7CA842852BB3",
					"name": "65e0810a690e52a87269"
				}],
				"lessonName": [{
					"uuid": "BFD6E9E7-185F-450C-B64F-3A8760EB39D1",
					"title": "5fae8f6f"
				}]
			}*/
		}
	},
	props: {
		// 指派窗口的标题
		assignTitle: {
			type: String,
			required: true,
			default: '骚年，你需要定义一个标题'
		},
		// 指派的类型，（用户部门还是课程指派）
		assignType: {
			type: String,
			required: true,
		},
		// 按用户指派时，tab展示控制
		userShowTab:{
			type:Object,
		},
		// 搜索框默认文字
		searchTipText: {
			type: String,
			default: '搜索'
		},
		// 默认渲染的数据
		showData:{
			type:Object,
			required:true,
		},
		// 指派窗口显示状态
		showStatus:{
			type:Boolean
		},
		// 部门是否可以勾选
		deptCheckbox:{
			type:Boolean,
			default:true
		},
		//已选中标签key
		checkedKeys:{
			type:Array,
		}
	},
	components: {
		assignSearch,
	},
	methods: {
		// 全选
		selectAll() {
			// 对应tab分类全选状态
			this.checkall[this.type] = !this.checkall[this.type];
			// if (this.checkall[this.type]) {
				switch (this.type){
					// 课程类全选
					case 'lesson':
						this.assignShowData.lessonName.forEach( item => {
							// 判断之前记录的数据中是否存在
							if (this.record.indexOf(item.uuid) < 0 && this.checkall[this.type]) {
								this.add(item.uuid, item.title, item);
							}else if(this.record.indexOf(item.uuid) > 0 && !this.checkall[this.type]){
								this.del(item.uuid)
							}
						});
						break;

					// 部门、用户全选
					case 'user':
						if(this.deptCheckbox){
							this.assignShowData.deptList.forEach( item => {
								if (this.record.indexOf(item.uuid) < 0 && !item.disable && this.checkall[this.type]) {
									this.add(item.uuid, item.dept_name, item);
								}else if(this.record.indexOf(item.uuid) > 0 && !this.checkall[this.type]){
								this.del(item.uuid)
							}
							});
						}
						this.assignShowData.userList.forEach( item => {
							if (this.record.indexOf(item.uuid) < 0 && this.checkall[this.type]) {
								this.add(item.uuid, item.user_name, item);
							}else if(this.record.indexOf(item.uuid) > 0 && !this.checkall[this.type]){
								this.del(item.uuid)
							}
						});
						break;

					// 用户组全选
					case 'group':
						this.assignShowData.showList.forEach( item => {
							if (this.record.indexOf(item.uuid) < 0 && this.checkall[this.type]) {
								this.add(item.uuid, item.name, item);
							}else if(this.record.indexOf(item.uuid) > 0 && !this.checkall[this.type]){
								this.del(item.uuid)
							}
						});
						break;

					//按职位全选
					case 'position':
						this.assignShowData.showList.forEach( item => {
							if (this.record.indexOf(item.uuid) < 0 && this.checkall[this.type]) {
								this.add(item.uuid, item.name, item);
							}else if(this.record.indexOf(item.uuid) > 0 && !this.checkall[this.type]){
								this.del(item.uuid)
							}
						});
						break;
				}
			/*} else {
				this.record = [];
				this.recordAll = [];
				this.checkStatus = {};
				this.rightShowInfo = [];
			}*/
		},
		//根据uuid执行添加操作 
		add(uuid, name, item) {
			this.record.push(uuid);
			this.recordAll.push(item);
			this.$set(this.checkStatus, uuid, true);
			let obj = {
				uuid: uuid,
				title: name
			}
			this.rightShowInfo.push(obj);
		},
		// 根据uuid执行删除操作 
		del(uuid) {
			let exist = this.record.indexOf(uuid);
			// 移出记录数组中的标识
			this.record.splice(exist, 1);
			// 将当前checkbox状态改为false
			this.$set(this.checkStatus, uuid, false);
			// 取消对应分类的全选状态
			this.checkall[this.type] = false;
			// 过滤掉取消的数据
			this.recordAll = this.recordAll.filter(function(item) {
				return item.uuid != uuid;
			});
			this.rightShowInfo = this.rightShowInfo.filter(function(item) {
				return item.uuid != uuid;
			});
		},
		// 点击课程分类时，记录其信息
		selectLesson(uuid, name, item,ele) {
			// 判断此部门是否禁止选中
			let disableState = false;
			if(ele){
				disableState = $(ele.target).parents('.lesson-name').children("label").attr("aria-disabled");
			}
			// 判断此数据之前是否选中
			let exist = this.record.indexOf(uuid);

			// 不存在则记录，存在则删除其记录信息
			if (exist < 0 && !disableState) {
				this.add(uuid, name, item);
			} else {
				this.del(uuid);
			}
		},
		// 监听搜索子组件中的选中事件
		selectSearchChild (param,item) {
			let exist = this.record.indexOf(param.uuid);
			// 不存在则记录，存在则删除其记录信息
			if (exist < 0) {
				this.add(param.uuid, param.name, item);
			}
			// 置空搜索框，隐藏搜索结果模块
			this.searchwords = '';
		},
		// 右侧信息删除方法
		deleteLesson(uuid) {
			this.del(uuid);
		},
		// 点击课程分类下级,获取下级数据
		next(uuid, name, ele) {
			let _self = this;
			// 部门选中，禁用下级点击
			let exist = this.record.indexOf(uuid);
			if(exist >= 0 || $(ele.target).hasClass('disable-click')) return false;

			this.assignShowData={
				 "deptList": [
				 	{
			            "uuid"         : "22034553",
			            "dept_name"    : "4e007ea790e895e8",
			            'has_children' : 0,
			        },
			    ],
				"userList": [
			        {
			            "dept_user_name": "4e0d591f",
			            "user_name": "4e0d591f",
			            "position": "",
			            "uuid": "0FE73D86-ECDF-4284-A1A3-DD41B14446F4",
			        }
			    ]
			}
			return false;
			setTimeout(() => {
				// 回调成功后，赋值显示数据，并追加到顶部小导航
				// this.assignShowData = requestdata;
				_self.$_get("user/admin/v1/contacts/department", { parent_id:uuid }).then(function(res) {
			        if (res.status == 'ok') {
			          	let resData = res.data;
			          	_self.assignShowData.deptList = resData.list;
			        }
			    });
			    _self.$_get("user/admin/v1/contacts/departmentUser", { dept_id:uuid }).then(function(res) {
			        if (res.status == 'ok') {
			        	let resData = res.data;
			          	_self.assignShowData.userList = resData.list;
			        }
			    });

				let obj = {
					uuid: uuid,
					name: name
				}

				// 面包屑增加导航数据
				this.navInfo.push(obj);

				// 给面包屑导航添加蓝色标记
				this.$nextTick().then(() => {
					$(".nav-com").not(":last-child").addClass('nav-blue');
				})
			}, 500)
		},

		// 顶部小导航点击方法
		navClick() {
			let _self = this;
			$('.left-nav').on('click', '.nav-blue', function() {
				var iden = $(this).data('iden');
				_self.loading = true;
				setTimeout(()=>_self.loading=false,2000)
				//移除所点击课程分类后面的导航
				$(this).removeClass('nav-blue');
				$(this).nextAll().remove();

				// 测试代码
				_self.lesson = _self.lessonExam;

				// 请求新数据
				/* $.post($("#choice").data('url'), { parentId:iden } , function(data) {
				    _self.defaultShow(data.lessonType, data.lessonName);
				 });*/
			});
		},
		// 切换tab操作
		changeTab (e){
			let $this = $(e.target);
			let type = $this.data('type');
			this.type = type;

			$this.addClass("by-sec").siblings().removeClass("by-sec");

			// 默认数据未请求过，则进行请求
			if(this.requestStatus[type]){
				// 进行请求
				setTimeout( () => {
					// this.assignShowData = requestdata;
					alert('切换tab，在此处请求数据')
					// 请求成功后，将对应的tab请求状态设置为false，缓存默认请求
					this.requestStatus[type] = false;
					
				},500)
			}
		},
		// 确定
		ok (){
			this.$emit('ok',this.recordAll);
		},
		// 取消
		cancel (){
			this.$emit('update:showStatus', false)
		},
		// 搜索框占位符动画效果
		placeMove (type){
			if(type=='focus'){
				$(".place-text").addClass('place-move');
			}else if(type=='blur' && this.searchwords==''){
				$(".place-text").removeClass('place-move');
			}
		},
		// 编辑时标记数据选中状态
		sign (){
			let keys = Object.keys(this.assignShowData);
			
			keys.forEach( (item) => {
				this.assignShowData[item].forEach( (item2) => {
					if(this.checkedKeys.length>0 && $.inArray(item2.uuid, this.checkedKeys)!=-1){
						this.add(item2.uuid, item2.show_name, item2);
					}
					// if(item2.checked === true){
					// 	this.add(item2.uuid, item2.show_name, item2)
					// }
				})
			})
		},
	},
	watch :{
		assignShowData (){
			// 渲染数据变化时，执行标记方法
			this.sign();
		}
	},
	mounted() {
		// 初始化给第一个tab增加默认选中
		$(".right-tab span").eq(0).addClass('by-sec');

		// 设置初始化渲染数据
		this.assignShowData =  this.showData;

		// 绑定面包屑导航点击事件
		this.navClick(); 
	}
}

</script>
<style lang="less">
@import './less/assign.less';
.slide {
	transition: .3s all;
	z-index: 100;
}
.slide-enter,
.slide-leave-active {
	opacity: 0;
	transform: translateY(20px);
}
.user-height{height: 322px !important;}
.disable-click{
	color:#a9a7a7 !important;
}
.dept-span{
	&>input{
		width: 16px;
		height: 16px;
		margin-right: 4px;
	}
}
.place-text{
	position: absolute;
	left: 24px;
	top: 7px;
	transition:.3s all;
	padding: 0 4px;
	color:#808080;
	background-color: #fff;
	z-index: 1;
}
.place-move{
	color:#9a9999;
	transform:translateY(-19px);
}
.el-checkbox.xcheck{
	width: 233px;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}
.deptCheck{
	width: 200px;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}
 .right-list-item{
 	display: block;
	width: 100%;
	transition:all .3s;
} 
.right-list-enter, .right-list-leave-to{
	opacity:0;
	transform:translateX(20px);
}
.right-list-leave-active{
	position: absolute !important;
}
.right-all{overflow: hidden;}
</style>
